package com.newidea.facillty.restful;

import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@Data
public class ApiResult<T> {
    private ApiResultState state;
    private T data;

    public ApiResult(){}

    public ApiResult(final int code, final String message) {
        this.state = ApiResultState.build(code, message);
    }

    public ApiResult(final int code, final String message, final T data) {
        this.state = ApiResultState.build(code, message);
        this.data = data;
    }

    public static <T> ResponseEntity<ApiResult<T>> ok(T data) {
        ApiResult<T> apiResult = new ApiResult<>();
        apiResult.state = ApiResultState.ok();
        apiResult.data = data;
        return ResponseEntity.ok(apiResult);
    }

    public static <T> ResponseEntity<ApiResult<Object>> ok() {
        return build(HttpStatus.OK, ApiResultState.CODE_SUCCESS, ApiResultState.DESC_SUCCESS);
    }

    public static <T> ResponseEntity<ApiResult<Object>> build(final HttpStatus status, final String message) {
        return ResponseEntity
            .status(status)
            .contentType(MediaType.APPLICATION_JSON)
            .body(new ApiResult<>(status.value(), message));
    }

    public static <T> ResponseEntity<ApiResult<T>> build(final HttpStatus status, final String message, final T data) {
        return ResponseEntity
            .status(status)
            .contentType(MediaType.APPLICATION_JSON)
            .body(new ApiResult<>(status.value(), message, data));
    }

    public static <T> ResponseEntity<ApiResult<Object>> build(
        final HttpStatus status, final int code, final String message
    ) {
        return ResponseEntity
            .status(status)
            .contentType(MediaType.APPLICATION_JSON)
            .body(new ApiResult<>(code, message));
    }

    public static <T> ResponseEntity<ApiResult<T>> build(
        final HttpStatus status, final int code, final String message, final T data
    ) {
        return ResponseEntity
            .status(status)
            .contentType(MediaType.APPLICATION_JSON)
            .body(new ApiResult<>(code, message, data));
    }

    public static <T> ApiResult<T> build(final int code, final String message) {
        return new ApiResult<>(code, message);
    }

    public static <T> ApiResult<T> build(final int code, final String message, final T data) {
        return new ApiResult<>(code, message, data);
    }

    public static <T> ApiResult<T> of(final int code, final String message) {
        return new ApiResult<>(code, message);
    }

    public static <T> ApiResult<T> of(final int code, final String message, final T data) {
        return new ApiResult<>(code, message, data);
    }

    public boolean isOk() {
        return state.getCode() == ApiResultState.CODE_SUCCESS;
    }
}
